package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.addressMapper;
import com.sky.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/addressBook")
@Slf4j
@Api(value = "用户地址接口")
public class addressController {
    @Autowired
    private addressMapper addressMapper;
    @GetMapping("/list")
    @ApiOperation("查看登陆用户所有地址")
    public Result lookById(){
        List<AddressBook> addressBooks = addressMapper.selectByUserId(BaseContext.getCurrentId());
        return Result.success(addressBooks);
    }
    @ApiOperation("新增地址")
    @PostMapping()
    public Result add(@RequestBody AddressBook addressBook){
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressMapper.addNewAddress(addressBook);
        return Result.success();
    }
    @ApiOperation("查询默认地址")
    @GetMapping("/default")
    public Result defaultAddressBook(){
        AddressBook addressBook = addressMapper.selectDefault(BaseContext.getCurrentId());
        return Result.success(addressBook);
    }
    @ApiOperation("根据id查询地址信息")
    @GetMapping("/{id}")
    public Result findById(@PathVariable Integer id){
        AddressBook addressBook = addressMapper.selectById(id);
        return Result.success(addressBook);
    }

    @ApiOperation("根据id修改地址")
    @PutMapping()
    public Result update(@RequestBody AddressBook addressBook){
       addressMapper.update(addressBook);
       return Result.success();
    }

    @DeleteMapping()
    @ApiOperation("根据id删除地址")
    public Result delete( Integer id){
        addressMapper.delete(id);
        return Result.success();
    }

    @ApiOperation("设置默认地址")
    @PutMapping("/default")
    public Result updateDefault(@RequestBody AddressBook id){
        //将本用户的默认地址更改
        //AddressBook build = AddressBook.builder().userId(BaseContext.getCurrentId()).isDefault(0).build();
        id.setIsDefault(0);
        Long id1 = id.getId();
        id.setId(null);
        id.setUserId(BaseContext.getCurrentId());
        addressMapper.update(id);
        id.setIsDefault(1);
        id.setId(id1);
        addressMapper.update(id);
        return Result.success();

    }

}
